package cn.tedu.contorller;

import cn.tedu.dao.BannerDao;
import cn.tedu.entity.Banner;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@MultipartConfig
@WebServlet("/AddBannerServlet")
public class AddBannerServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        Part part = request.getPart("file");
        String str = part.getHeader("Content-disposition");
        String suffix = str.substring(str.indexOf("."),str.length()-1);
        //给上传的图片一个唯一的名字
        String fileName = UUID.randomUUID()+suffix;
        //获取图片保存路径
        String localPath = "E:/IDEATomcat8.5/apache-tomcat-8.5.45/webapps/imgs/";


        String imgPath = localPath+fileName;
        part.write(imgPath);

        //网络访问路径
        String urlPath = "http://localhost:8080/imgs/"+fileName;


        BannerDao dao = new BannerDao();
        dao.insert(new Banner(0,urlPath));

        response.sendRedirect(request.getContextPath()+"/ShowBannerServlet");
    }

}
